import React from "react";
import {
  Button,
  Table,
  Upload,
  message,
  Switch,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Tooltip,
  Modal
} from "antd";
import config from "config";
import Chooser from "components/chooser";
import httpFetch from "share/httpFetch";
import ExportModal from "components/template/export-modal/export-modal";
import moment from "moment";
import { deepFullCopy, formatNumber } from "share/common";
import ResizeTable from "components/resize-table";
import { messages } from "share/common";
const { confirm } = Modal;
const { Option } = Select;
const ButtonGroup = Button.Group;

export default class UnifiedTable extends React.Component {
  constructor(props) {
    super(props);
    // console.log("UnifiedTable constructor props", props);
    const {
      lineEdit: propsLineEdit,
      exportFile: propsExportFile,
      showIndex = false,
      maxPageSize,
      readonly = false,
    } = props;
    const columns = showIndex
      ? [
          {
            ellipsis: true,
            title: "序号",
            dataIndex: "index",
            width: 50,
            key: "index",
            render: (cell, row, index) => `${index + 1}`,
          },
        ]
      : [];
    let pageSize = 10;
    let lineEdit = propsLineEdit !== false && propsLineEdit !== "false";
    const exportFile = propsExportFile === true || propsExportFile === "true";

    // TODO 开发完抽屉编辑之前，始终使用行编辑
    lineEdit = true;

    let dataPool = {};
    try {
      dataPool = JSON.parse(props.dataPool);
    } catch (e) {
      if (config.appEnv === "dev") {
        console.warn("UnifiedTable", e.message);
      }
    }

    try {
      pageSize = parseInt(maxPageSize, 10);
      if (isNaN(pageSize)) {
        pageSize = 10;
      } else if (pageSize > 100 || pageSize < 1) {
        pageSize = 10;
      }
    } catch (e) {}

    try {
      const formFields = JSON.parse(props.formField);
      if (Array.isArray(formFields)) {
        this.formFields = formFields;
      } else {
        this.formFields = [];
      }
    } catch (e) {
      this.formFields = [];
    }

    try {
      this.formFields.forEach((field, k) => {
        if (field.visible === 0) return;
        const { columnComment, columnName } = field;
        columns.push({
          ellipsis: true,
          title: <div className={columnName === 'reason' ? '' : (columnName === 'remark' && this.props.isRemarkRequired) ? '' : "red-with-star"}>{columnComment || columnName}</div>,
          dataIndex: columnName,
          key: columnName,
          render: (value, record, index) => {
            if (field.widgetType === 0) {
              if (readonly) {
                if (field.showTooltip || field.columnName === 'remark') {
                  return <Tooltip title={record[field.columnName]}>{record[field.columnName]}</Tooltip>
                } else {
                  return record[field.columnName]
                }
              }
              if (field.columnName === 'reason' && !this.reasonReadOnly[index]) {
                return '-'
              }
              return (
                <Input
                  size="small"
                  value={record[field.columnName]}
                  onChange={(e) => {
                    this.updateRow({
                      index,
                      columnName,
                      value: e.target.value,
                    });
                  }}
                />
              );
            }
            if (field.widgetType === 1) {
              if (readonly) return (columnName === 'amount' || columnName === 'baseCurrencyAmount') ? formatNumber(record[field.columnName]) : record[field.columnName];
              return (
                <InputNumber
                  size="small"
                  value={record[field.columnName]}
                  formatter={(columnName === 'amount' || columnName === 'baseCurrencyAmount') ? value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : ''}
                  onChange={(e) => {
                    this.updateRow({
                      index,
                      columnName,
                      value: e,
                    });
                  }}
                />
              );
            }
            if (field.widgetType === 2) {
              if (readonly) return record[field.columnName] === 1 ? "是" : "否";

              return (
                <Switch
                  size="small"
                  checked={record[field.columnName] === 1}
                  onChange={(e) => {
                    this.updateRow({
                      index,
                      columnName,
                      value: e ? 1 : 0,
                    });
                  }}
                />
              );
            }
            if (field.widgetType === 3) {
              if (readonly) {
                if (typeof value === "undefined") return "-"; //未选择
                if (typeof value === "string") return value;
              }
              console.log("this.props.SQ001readOnly", this.props.SQ001readOnly)
              if (this.props.SQ001readOnly && this.props.SQ001readOnly[k] && field.columnName === 'custom_enumeration_item_oid' || this.props.status === 1002 || this.props.status === 1003) {
                // console.log('record[field.columnName]', record[field.columnName])
                return record[field.columnName].name
              }
              return (
                <Chooser
                  size="small"
                  selectorItem={{
                    key: "code",
                    title: "选择",
                    columns: field.columnName === 'custom_enumeration_item_oid' ? [
                      { title: "名称", dataIndex: "messageKey" },
                    ] : [
                      // {
                      //   title: "编码",
                      //   dataIndex: "code",
                      // },
                      { title: "名称", dataIndex: "messageKey" },
                    ],
                    searchForm: [],
                    url: `${config.baseUrl}/api/public/assembly/custom/enumerations/${field.dataSource.code}`,
                  }}
                  value={value && value.name ? [value] : []}
                  onChange={(chooserValue) => {
                    if (chooserValue.length > 0) {
                      const item = chooserValue[0];
                      const nextDataSource = {
                        messageKey: item.messageKey,
                        name: item.messageKey,
                        code: item.code,
                      };
                      this.updateRow({
                        index,
                        columnName,
                        value: nextDataSource,
                      });
                    } else {
                      this.updateRow({
                        index,
                        columnName,
                        value: {},
                      });
                    }
                  }}
                  single
                  valueKey="code"
                  labelKey="messageKey"
                />
              );
            }
            if (field.widgetType === 4) {
              if (readonly) {
                if (typeof value === "undefined") return "-"; //未选择
                if (typeof value === "string") return value;
                return value.name || value.messageKey || value.code;
              }
              return (
                <Chooser
                  size="small"
                  selectorItem={{
                    key: "code",
                    title: "选择",
                    columns: [
                      // {
                      //   title: "编码",
                      //   dataIndex: "code",
                      // },
                      { title: "名称", dataIndex: "messageKey" },
                    ],
                    searchForm: [],
                    url: `${config.baseUrl}/api/public/assembly/custom/enumerations/${field.dataSource.code}`,
                  }}
                  value={value ? [value] : []}
                  onChange={(chooserValue) => {
                    if (chooserValue.length > 0) {
                      const item = chooserValue[0];
                      const nextDataSource = {
                        messageKey: item.messageKey,
                        name: item.messageKey,
                        code: item.code,
                      };
                      this.updateRow({
                        index,
                        columnName,
                        value: nextDataSource,
                      });
                    } else {
                      this.updateRow({
                        index,
                        columnName,
                        value: undefined,
                      });
                    }
                  }}
                  single
                  valueKey="code"
                  labelKey="messageKey"
                />
              );
            }
            if (field.widgetType === 5) {
              if (value === undefined) {
                value = moment().format('YYYY-MM-DD');
                this.updateRow({
                  index,
                  columnName,
                  value: value,
                })
              }
              if (readonly) return value;
              // console.log('date picker value', value)
              return (
                <DatePicker
                  size={'small'}
                  value={moment(value)}
                  placeholder="选择日期"
                  onChange={(datePickerValue) => {
                    // console.log('datePickerValue', datePickerValue)
                    this.updateRow({
                      index,
                      columnName,
                      value: datePickerValue.format("YYYY-MM-DD"),
                    });
                  }}
                />
              );
            }
            return null;
          },
        });
      });
      if (!readonly) {
        columns.push({
          ellipsis: true,
          title: "操作",
          dataIndex: "_operate",
          key: "_operate",
          render: (value, record, index) => {
            return (
              <ButtonGroup>
                {!lineEdit && (
                  <Button size="small" type="primary" ghost>
                    编辑
                  </Button>
                )}
                <Button
                  size="small"
                  type="danger"
                  ghost
                  // icon="delete"
                  onClick={() => {
                    this.handleDeleteRow({ index });
                  }}
                >
                  删除
                </Button>
              </ButtonGroup>
            );
          },
        });
      }
    } catch (e) {
      if (config.appEnv === "dev") {
        console.error(e);
      }
    }

    this.state = {
      dataPool,
      templateUrl: props.templateUrl,
      fileList: [],
      data: this.getDataFromValue(props.value),
      tableVersion: 0,
      tableUploading: false,
      pagination: {
        showLessItems: true,
        current: 1,
        showTotal: (total, range) => (
          <div style={{ display: "flex", alignItems: "center" }}>
            {exportFile && (
              <ExportModal
                type="btn"
                btnSize="small"
                btnIcon="download"
                exportTitle={"导出"}
                exportType={"PUBLIC_ASSEMBLY"}
                exportCommand={"PUBLIC_ASSEMBLY"}
                exportCondition={{
                  publicSourceCommand: {
                    data: this.state.data,
                    formFields: this.formFields,
                  },
                }}
              />
            )}
            &nbsp;&nbsp; {`共${total}条记录`}
          </div>
        ),
        pageSize,
        onChange: (page) => {
          this.setState(({ pagination }) => {
            return {
              pagination: {
                ...pagination,
                current: page,
              },
            };
          });
        },
      },
    };
    this.value = this.props.value;
    this.columns = columns;
    this.reasonReadOnly = [];
  }

  componentDidUpdate(prevProps) {
    if (prevProps.value !== this.props.value) {
      if (this.value !== this.props.value) {
        if (config.appEnv === "dev") {
          // console.log("更新data");
        }
        this.setState({ data: this.getDataFromValue(this.props.value) });
      }
    }
    if (prevProps.templateUrl !== this.props.templateUrl) {
      console.warn(
        `templateUrl changed from ${prevProps.templateUrl} to ${this.props.templateUrl}`
      );
    }
  }

  getFileUid = () => {
    if (!this.fileUid) {
      this.fileUid = 1;
    }
    return `uid_${++this.fileUid}`;
  };

  getDataFromValue = (value) => {
    let data = [];
    try {
      if (value) {
        if (typeof value === "string") {
          data = JSON.parse(value);
        } else {
          data = value;
        }
        if (!Array.isArray(data)) {
          data = [];
        }
      }
    } catch (e) {
      if (config.appEnv === "dev") {
        console.error(e);
      }
    }
    // console.log("data", data);
    const result = [];
    for (let i = 0; i < data.length; i++) {
      if (data[i]) {
        const keys = Object.keys(data[i]);
        const record = {};
        for (let j = 0; j < keys.length; j++) {
          const key = keys[j];
          const fieldConfig = this.formFields.find(
            (field) => field.columnName === key
          );
          if (fieldConfig) {
            const cell = data[i][key];
            if (fieldConfig.widgetType === 0) {
              if (cell && cell.length > 0) record[key] = cell;
            } else if (fieldConfig.widgetType === 1) {
              const float = parseFloat(cell);
              if (!isNaN(float)) {
                record[key] = float;
              }
            } else if (fieldConfig.widgetType === 2) {
              record[key] = (cell === "是" || cell === 1 || cell === "1") ? 1 : 0;
            } else if (fieldConfig.widgetType === 5) {
              record[key] = cell;
            } else if (typeof cell !== "string") {
              // console.log("expected got string value, but got", cell);
            } else if (cell.length > 0) {
              record[key] = {
                code: cell,
                name: cell,
                messageKey: cell,
              };
            }
          }
        }
        result.push(record);
      }
    }
    // console.log("Parse data from raw value", JSON.stringify(result, null, 2));
    console.log("result", result)
    let list = [];
    result.map((item, k) => {
      if (item.beyond) {
        if (item.reason) {
          list.push(true)
        } else {
          list.push(false)
        }
      } else {
        list.push(false)
      }
    })
    console.log('reasonReadOnly', list)
    this.reasonReadOnly = list;
    return result;
  };

  handleFileChange = (event) => {
    const files = event.fileList;
    if (files.length === 0) {
      return;
    }
    // https://pmo.mcd.com.cn/jira/browse/TES-1431
    const { excleType } = this.props;
    let excelFunc = () => {
      this.setState({ tableUploading: { tip: "正在导入..." } });
      const file = files[0];
      const { excleType } = this.props;
      let url = `/api/public/assembly/readExcle`;
      if (excleType === 1 || excleType === 2) {
        url = '/api/public/assembly/readExcle2' + '?type=' + excleType
      }
      const form = new FormData();
      form.append("file", file);
      httpFetch
        .post(url, form)
        .then((res) => {
          const rows = res.data.rows || [];
          let trueRows = rows.filter(item => !item.error)
          let errorRows = rows.filter(item => item.error)
          const parsedData = this.getDataFromValue(trueRows);
          const importedNum = parsedData.length;

          this.setState((state) => {
            let nextData = [];
            if (excleType === 1 || excleType === 2) {
              nextData = [...parsedData];
            } else {
              nextData = [...state.data, ...parsedData];
            }
            // console.log(
            //   `state.data.length is ${state.data.length}, nextData.length is ${nextData.length}`
            // );
            if (errorRows && errorRows[0]) {
              message.warning(errorRows[0].error);
            } else {
              message.success(`本次导入${importedNum}条数据`);
            }
            console.log('nextData', nextData)
            return {
              tableUploading: false,
              data: nextData,
              tableVersion: state.tableVersion + 1,
              pagination: {
                ...state.pagination,
                current: Math.ceil(
                  (nextData.length ) / state.pagination.pageSize
                ),
              }
            };
          }, this.emitChange);
        })
        .catch((e) => {
          this.setState({ tableUploading: false });

          const response = e.response;
          if (response && response.data && response.data.message) {
            message.error(response.data.message);
          } else {
            message.error("解析失败");
          }
        });
    }
    if (this.state.data.length && (excleType === 1 || excleType === 2)) {
      confirm({
        title: messages('common.info',/* 提示 */),
        content: messages('components.key1342',/* 友情提示，导入人员清单，历史导入的数据会自动清空，请确保最新导入数据完整无误，是否导入？" */),
        okText: messages('common.ok',/* 确定 */),
        cancelText: messages('common.cancel',/* 取消 */),
        onOk: () => {
          excelFunc()
        }
      })
    } else {
      excelFunc()
    }
  };

  emitChange = () => {
    const { onChange } = this.props;
    if (onChange) {
      const { data } = this.state;
      // console.log(`current data length is ${data.length}`, data);
      const output = [];
      for (let i = 0; i < data.length; i++) {
        const outputRecord = {};
        const record = data[i];
        const keys = Object.keys(record);
        for (let j = 0; j < keys.length; j++) {
          const key = keys[j];
          const cell = record[key];
          const fieldConfig = this.formFields.find(
            (item) => item.columnName === key
          );
          if (!fieldConfig) {
            if (config.appEnv === "dev") {
              // console.log("FieldConfig not found for column: ", key);
            }
            continue;
          }
          // console.log(`fieldConfig ${fieldConfig.widgetType}`)
          if (fieldConfig.widgetType < 3 || fieldConfig.widgetType === 5) {
            outputRecord[key] = cell;
          } else if (typeof cell === "object" && !!cell) {
            outputRecord[key] = cell.name || cell.messageKey;
          }
        }
        const tempObj = deepFullCopy(outputRecord);
        Object.keys(outputRecord).map((key) => {
          // 去掉value为空字符串的key
          if (outputRecord[key] === "") {
            delete tempObj[key];
          }
        });
        if (Object.keys(tempObj).length > 0) {
          // 只有非空JSON可以被设置成value
          output.push(tempObj);
        }
      }
      this.value = JSON.stringify(output);
      // console.log(`emit ${output.length} records`);
      onChange(this.value);
    }
  };

  updateRow = (params) => {
    const { index, columnName, value } = params;
    this.setState(({ data, pagination }) => {
      const nextData = data.slice();
      const realIndex = index + (pagination.current - 1) * pagination.pageSize;
      nextData[realIndex] = { ...nextData[realIndex], [columnName]: value };
      if (columnName === 'beyond') {
        if (value) {
          this.reasonReadOnly[realIndex] = true;
        } else {
          this.reasonReadOnly[realIndex] = false;
        }
      }
      return {
        data: nextData,
      };
    }, this.emitChange);
  };

  handleDeleteRow = (params) => {
    const { index } = params;
    this.setState(({ data, tableVersion, pagination }) => {
      const realIndex = index + (pagination.current - 1) * pagination.pageSize;
      const nextData = data.slice();
      const isInLastPage =
        pagination.current === Math.ceil(nextData.length / pagination.pageSize);
      nextData.splice(realIndex, 1);
      return {
        data: nextData,
        tableVersion: tableVersion + 1,
        pagination: {
          ...pagination,
          current: isInLastPage
            ? Math.ceil(nextData.length / pagination.pageSize)
            : pagination.current,
        },
      };
    }, this.emitChange);
  };

  handleAddRow = () => {
    this.setState(({ data, pagination }) => {
      let isTrue = false;
      this.props.formField && JSON.parse(this.props.formField).map(item => {
        if(item.columnComment === '乘机人') {
          isTrue = true
        }
      })
      if (isTrue) {
        return {
          pagination: {
            ...pagination,
            current: Math.ceil((data.length + 1) / pagination.pageSize),
          },
          data: [...data, {
            remark: this.props.user.fullName
          }],
        };
      } else {
        return {
          pagination: {
            ...pagination,
            current: Math.ceil((data.length + 1) / pagination.pageSize),
          },
          data: [...data, {}],
        };
      }
    }, this.emitChange);
  };

  handleDownloadTemplate = () => {
    // console.log("UnifiedTable handleDownloadTemplte", this.props);
    const { templateUrl } = this.state;
    if (!templateUrl) {
      return message.error("模板不存在");
    }
    const link = document.createElement("a");
    link.style.display = "none";
    link.download = true;
    link.href = templateUrl;
    link.click();
    return null;
  };

  render() {
    const { tableVersion, key } = this.state;
    const { cellMinWidth = 150, readonly = false } = this.props;
    console.log('this.state.data', this.state.data)
    return (
      <div>
        <ResizeTable
          columns={this.columns}
          key={key}
          minSize={cellMinWidth}
          scroll={{ x: this.columns.length * cellMinWidth }}
          dataSource={this.state.data}
          loading={this.state.tableUploading}
          rowKey={(record, index) => `${tableVersion}_${index}`}
          pagination={this.state.pagination}
          bordered
          size="small"
          footer={
            readonly
              ? () => null
              : () => (
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                    }}
                  >
                    <div>
                      <div
                        style={{
                          display: this.props.importFile ? "flex" : "none",
                        }}
                      >
                        <Upload
                          multiple={false}
                          accept=".xls,.xlsx"
                          beforeUpload={() => false}
                          onChange={this.handleFileChange}
                        >
                          <Button size="small" icon="upload">
                            导入
                          </Button>
                        </Upload>
                        <Button
                          type="link"
                          size="small"
                          onClick={this.handleDownloadTemplate}
                          ghost
                        >
                          下载模板
                        </Button>
                      </div>
                    </div>

                    <Button
                      onClick={this.handleAddRow}
                      icon="plus"
                      size="small"
                    >
                      增加
                    </Button>
                  </div>
                )
          }
        />
        <style>
          {`
form .ant-select:only-child.ant-select-sm, form .ant-cascader-picker:only-child.ant-select-sm, form .ant-select:only-child.ant-cascader-picker-small, form .ant-cascader-picker:only-child.ant-cascader-picker-small {
  top: 0;
}
`}
        </style>
      </div>
    );
  }
}

UnifiedTable.defaultProps = {
  readonly: false,
  importFile: true,
  exportFile: false,
};

UnifiedTable.propTypes = {
  /**
   * @type {boolean}
   */
  readonly: React.PropTypes.boolean,

  /**
   * @deprecated 之前作为导出接口的参数，现在改用了其他参数，不需要dataPool了
   */
  dataPool: React.PropTypes.string,
  /**
   * formField的数据结构见
   * @see ./UnifiedTableConfig.js
   */
  formField: React.PropTypes.string,
  /**
   * @not_implemented
   */
  lineEdit: React.PropTypes.boolean,
  /**
   * 是否支持导入
   * @type {boolean}
   */
  importFile: React.PropTypes.boolean,

  exportFile: React.PropTypes.boolean,

  maxPageSize: React.PropTypes.number,

  /**
   * 是否显示序号
   * @type {boolean}
   */
  showIndex: React.PropTypes.boolean,

  /**
   * 单元格最小宽度
   * @type {number}
   */
  cellMinWidth: React.PropTypes.number,
};
